package com.ruoyi.system.execute;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysDictTypeMapper;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName DictLoader
 * @Description
 * @Author sizegang
 * @Date2025/4/18 23:49
 **/
@Component
public class DictCacheManager implements InitializingBean {
    @Autowired
    private SysDictTypeMapper sysDictTypeMapper;

    @Autowired

    private ISysDictDataService iSysDictDataService;


    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    public static final Map<Long, String> DICT_CACHE = new HashMap<>();

    @Override
    public void afterPropertiesSet() {
        loadDictCache();
    }

    public void loadDictCache() {
        DICT_CACHE.clear();
        List<SysDictType> sysDictTypes = sysDictTypeMapper.selectDictTypeAll();
        sysDictTypes.parallelStream().forEach((x) -> {
            List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataByType(x.getDictType());
            sysDictDataList.stream().forEach((sysDictData -> DICT_CACHE.put(sysDictData.getDictCode(), sysDictData.getDictLabel())));
        });
    }

    /**
     * 获取字典缓存
     *
     * @param dictCode
     * @return
     */
    public String getDictByCode(Long dictCode) {
        String localDict = DICT_CACHE.get(dictCode);
        if (Objects.isNull(localDict)) {
            SysDictData sysDictData = iSysDictDataService.selectDictDataById(dictCode);
            if (Objects.nonNull(sysDictData)) {
                DICT_CACHE.put(sysDictData.getDictCode(), sysDictData.getDictLabel());
                return sysDictData.getDictLabel();
            }
        }
        return localDict;
    }

    public String getDictByCode(String dictCode) {
        Assert.notNull(dictCode, "dictCode is null");
        return getDictByCode(Long.parseLong(dictCode));
    }
}
